Page({
  data: {
    btnColor: ["#409eff", "#67c23a", "#909399", "#e6a23c", "#f56c6c", "#356c6c", "#351c6c", "#f093a9", "#a7c23a", "#104eff", "#10441f", "#a21233", "#503319"],
    id: "",
    userid: "",
    isAuth: {},
    detail: {},
    user: {},
    // baseUrl 配置
    baseUrl: "",
    // 页面加载状态
    pageLoading: true,
    initError: false
  },

  onLoad(options) {
    // 在 onLoad 中初始化 baseUrl，避免 computed 的深拷贝警告
    this.setData({
      id: options.id,
      baseUrl: this.getBaseUrl()
    });
    if (options.userid) {
      this.setData({
        userid: options.userid
      });
    }
  },

  // 获取 baseUrl 的方法
  getBaseUrl() {
    // 开发环境下使用本地IP，避免localhost无法访问的问题
    if (this.$base && this.$base.url) {
      return this.$base.url;
    }
    // 备用配置：使用本地IP地址，在小程序开发环境中更稳定
    return 'http://localhost:8080/springboot1u997/';
    // return 'http://192.168.1.11:8080/springboot1u997/';
  },

  onUnload() {
    if (this.data.timer != null) {
      clearInterval(this.data.timer);
    }
  },

  async onShow() {
    // 只在第一次加载或者没有详情数据时调用 init
    if (!this.data.detail || !this.data.detail.id) {
      await this.init();
    }
    
    try {
      const nowTable = wx.getStorageSync("nowTable");
      const res = await this.apiCall('session', nowTable);
      if (res && res.data) {
        this.setData({
          user: res.data
        });
      } else {
        // 备用方案：从本地存储获取用户信息
        const userInfo = wx.getStorageSync("userInfo") || {};
        this.setData({
          user: userInfo
        });
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 备用方案：从本地存储获取用户信息
      const userInfo = wx.getStorageSync("userInfo") || {};
      this.setData({
        user: userInfo
      });
    }
    
    this.setData({
      btnColor: this.data.btnColor.sort(() => 0.5 - Math.random())
    });
    
    this.getStoreup();
    this.getThumbsup();
    

  },



  // API 调用封装
  async callApi(url, method = 'GET', data = {}) {
    const baseUrl = this.data.baseUrl;
    console.log('API请求:', baseUrl + url);
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: baseUrl + url,
        method: method,
        data: data,
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token') || ''
        },
        success: (res) => {
          console.log('API响应:', res);
          
          // 检查业务状态码
          if (res.data && res.data.code === 401) {
            wx.showToast({
              title: '请先登录',
              icon: 'none'
            });
            resolve(null);
            return;
          }
          
          resolve(res.data);
        },
        fail: (error) => {
          console.error('API请求失败:', error);
          
          // 判断错误类型
          if (error.errMsg && error.errMsg.includes('invalid url')) {
            wx.showToast({
              title: '服务器连接失败，请检查网络',
              icon: 'none',
              duration: 3000
            });
          } else {
            wx.showToast({
              title: '网络请求失败',
              icon: 'none'
            });
          }
          
          reject(error);
        }
      });
    });
  },

  // 通用API方法封装，兼容原有的$api调用方式
  async apiCall(action, table, params = {}) {
    try {
      // 如果$api可用，优先使用
      if (this.$api && this.$api[action]) {
        return await this.$api[action](table, params);
      }
      
      // 备用方案：构建API URL并调用
      let url = '';
      let method = 'GET';
      let data = {};
      
      switch (action) {
        case 'info':
          url = `${table}/info/${params}`;
          break;
        case 'list':
          url = `${table}/list`;
          method = 'POST';
          data = params;
          break;
        case 'page':
          url = `${table}/page`;
          method = 'POST';
          data = params;
          break;
        case 'add':
          url = `${table}/save`;
          method = 'POST';
          data = params;
          break;
        case 'update':
          url = `${table}/update`;
          method = 'POST';
          data = params;
          break;
        case 'del':
          url = `${table}/delete`;
          method = 'POST';
          data = { ids: params };
          break;
        case 'session':
          url = `${table}/session`;
          break;
        default:
          throw new Error(`不支持的API操作: ${action}`);
      }
      
      return await this.callApi(url, method, data);
    } catch (error) {
      console.error(`API调用失败 [${action}:${table}]:`, error);
      wx.showToast({
        title: '操作失败，请稍后重试',
        icon: 'none'
      });
      return null;
    }
  },



  // 支付相关
  onPayTap() {
    wx.setStorageSync("paytable", "ershoushangpin");
    wx.setStorageSync("payObject", this.data.detail);
    wx.navigateTo({
      url: "../pay-confirm/pay-confirm?type=1"
    });
  },

  onDetailTap(e) {
    wx.setStorageSync("useridTag", this.data.userid);
    wx.navigateTo({
      url: `./detail?id=${e.id}&userid=${this.data.userid}`
    });
  },

  // 收藏功能
  async getStoreup() {
    try {
      if (!this.data.user.id) return;
      
      const params = {
        page: 1,
        limit: 1,
        refid: this.data.id,
        tablename: "ershoushangpin",
        userid: this.data.user.id,
        type: 1
      };
      
      let res;
      if (this.$api && this.$api.list) {
        res = await this.$api.list("storeup", params);
      } else {
        res = await this.callApi('/storeup/list', 'GET', params);
      }
      
      const list = res.data ? res.data.list : res.list || [];
      this.setData({
        storeupFlag: list.length
      });
    } catch (error) {
      console.error('获取收藏状态失败:', error);
    }
  },

  async shoucang() {
    try {
      if (!this.data.user.id) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      const params = {
        page: 1,
        limit: 1,
        refid: this.data.detail.id,
        tablename: "ershoushangpin",
        userid: this.data.user.id,
        type: 1
      };
      
      let res;
      if (this.$api && this.$api.list) {
        res = await this.$api.list("storeup", params);
      } else {
        res = await this.callApi('/storeup/list', 'GET', params);
      }
      
      const list = res.data ? res.data.list : res.list || [];
      
      if (list.length === 1) {
        const id = list[0].id;
        wx.showModal({
          title: "提示",
          content: "是否取消收藏",
          success: async (modalRes) => {
            if (modalRes.confirm) {
              try {
                if (this.$api && this.$api.del) {
                  await this.$api.del("storeup", JSON.stringify([id]));
                } else {
                  await this.callApi('/storeup/delete', 'POST', [id]);
                }
                wx.showToast({
                  title: '取消成功',
                  icon: 'success'
                });
                this.getStoreup();
              } catch (error) {
                wx.showToast({
                  title: '操作失败',
                  icon: 'none'
                });
              }
            }
          }
        });
      } else {
        wx.showModal({
          title: "提示",
          content: "是否收藏",
          success: async (modalRes) => {
            if (modalRes.confirm) {
              try {
                const storeupData = {
                  userid: this.data.user.id,
                  name: this.data.detail.shangpinmingcheng,
                  picture: this.data.detail.tupian || '',
                  refid: this.data.detail.id,
                  tablename: "ershoushangpin",
                  type: 1
                };
                
                if (this.$api && this.$api.add) {
                  await this.$api.add("storeup", storeupData);
                } else {
                  await this.callApi('/storeup/save', 'POST', storeupData);
                }
                
                wx.showToast({
                  title: '收藏成功',
                  icon: 'success'
                });
                this.getStoreup();
              } catch (error) {
                wx.showToast({
                  title: '操作失败',
                  icon: 'none'
                });
              }
            }
          }
        });
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 跨表操作
  onAcrossTap(table, obj, column, value, tips) {
    wx.setStorageSync("crossTable", "ershoushangpin");
    wx.setStorageSync("crossObj", this.data.detail);
    wx.setStorageSync("statusColumnName", column);
    wx.setStorageSync("statusColumnValue", value);
    wx.setStorageSync("tips", tips);
    
    if (column !== "" && !column.startsWith("[")) {
      const crossObj = wx.getStorageSync("crossObj");
      for (const key in crossObj) {
        if (key === column && crossObj[key] === value) {
          this.$utils.msg(tips);
          return;
        }
      }
    }
    wx.navigateTo({
      url: `../${table}/add-or-update?cross=true`
    });
  },

  // 初始化详情
  async init() {
    try {
      // 设置加载状态
      this.setData({
        pageLoading: true,
        initError: false
      });

      const res = await this.apiCall('info', 'ershoushangpin', this.data.id);
      
      // 如果返回null，说明需要登录
      if (res === null) {
        this.setData({
          pageLoading: false,
          initError: true
        });
        wx.showToast({
          title: '请先登录查看商品详情',
          icon: 'none',
          duration: 2000
        });
        setTimeout(() => {
          wx.navigateTo({
            url: '../login/login'
          });
        }, 2000);
        return;
      }
      
      const detail = res.data || res;
      if (!detail) {
        throw new Error('商品信息为空');
      }
      
      this.setData({
        detail: detail,
        pageLoading: false,
        initError: false
      });
      
      // 处理富文本图片
      if (detail.shangpinmiaoshu) {
        const desc = detail.shangpinmiaoshu.replace(/img src/gi, 'img style="width:100%;" src');
        this.setData({
          'detail.shangpinmiaoshu': desc
        });
      }
      
      console.log('商品详情初始化成功:', detail);
    } catch (error) {
      console.error('初始化详情失败:', error);
      this.setData({
        pageLoading: false,
        initError: true
      });
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    }
  },





  // 立即购买
  onBuyTap() {
    wx.setStorageSync("orderGoods", [{
      tablename: "ershoushangpin",
      goodid: this.data.detail.id,
      goodname: this.data.detail.shangpinmingcheng,
      chiwuzhanghao: this.data.detail.chiwuzhanghao,
      picture: this.data.detail.tupian || '',
      buynumber: 1,
      price: this.data.detail.price,
      discountprice: this.data.detail.vipprice
    }]);
    wx.navigateTo({
      url: "../shop-order-confirm/shop-order-confirm?type=1"
    });
  },

  // 聊天
  onChatTap() {
    wx.navigateTo({
      url: "../chat/chat"
    });
  },

  // 下载
  download(url) {
    url = this.$base.url + url;
    wx.downloadFile({
      url: url,
      success: (res) => {
        if (res.statusCode === 200) {
          this.$utils.msg("下载成功");
          // 小程序中无法直接打开文件，可以保存到相册或分享
        }
      }
    });
  },





  // 点赞相关
  async getThumbsup() {
    try {
      if (!this.data.user.id) return;
      
      const params = {
        page: 1,
        limit: 1,
        refid: this.data.id,
        tablename: "ershoushangpin",
        userid: this.data.user.id,
        type: "%2%"
      };
      
      let res;
      if (this.$api && this.$api.list) {
        res = await this.$api.list("storeup", params);
      } else {
        res = await this.callApi('/storeup/list', 'GET', params);
      }
      
      const list = res.data ? res.data.list : res.list || [];
      if (list.length > 0) {
        if (list[0].type === "21") {
          this.setData({ thumbsupFlag: 1 });
        } else {
          this.setData({ crazilyFlag: 1 });
        }
      }
    } catch (error) {
      console.error('获取点赞状态失败:', error);
    }
  },

  async zan() {
    const params = {
      page: 1,
      limit: 1,
      refid: this.data.detail.id,
      tablename: "ershoushangpin",
      userid: this.data.user.id,
      type: "%2%"
    };
    const res = await this.$api.list("storeup", params);
    
    if (res.data.list.length > 0) {
      const id = res.data.list[0].id;
      wx.showModal({
        title: "提示",
        content: "是否取消点赞",
        success: async (modalRes) => {
          if (modalRes.confirm) {
            await this.$api.del("storeup", JSON.stringify([id]));
            this.data.detail.thumbsupnum = parseInt(this.data.detail.thumbsupnum) - 1;
            await this.$api.update("ershoushangpin", this.data.detail);
            this.$utils.msg("取消成功");
            this.setData({ thumbsupFlag: 0 });
          }
        }
      });
    } else {
      wx.showModal({
        title: "提示",
        content: "是否点赞",
        success: async (modalRes) => {
          if (modalRes.confirm) {
            await this.$api.add("storeup", {
              userid: this.data.user.id,
              name: this.data.detail.shangpinmingcheng,
              picture: this.data.detail.tupian || '',
              refid: this.data.detail.id,
              tablename: "ershoushangpin",
              type: "21"
            });
            this.data.detail.thumbsupnum = parseInt(this.data.detail.thumbsupnum) + 1;
            await this.$api.update("ershoushangpin", this.data.detail);
            this.$utils.msg("点赞成功");
            this.setData({ thumbsupFlag: 1 });
          }
        }
      });
    }
  },

  async cai() {
    const params = {
      page: 1,
      limit: 1,
      refid: this.data.detail.id,
      tablename: "ershoushangpin",
      userid: this.data.user.id,
      type: "%2%"
    };
    const res = await this.$api.list("storeup", params);
    
    if (res.data.list.length > 0) {
      const id = res.data.list[0].id;
      wx.showModal({
        title: "提示",
        content: "是否取消点踩",
        success: async (modalRes) => {
          if (modalRes.confirm) {
            await this.$api.del("storeup", JSON.stringify([id]));
            this.data.detail.crazilynum = parseInt(this.data.detail.crazilynum) - 1;
            await this.$api.update("ershoushangpin", this.data.detail);
            this.$utils.msg("取消成功");
            this.setData({ crazilyFlag: 0 });
          }
        }
      });
    } else {
      wx.showModal({
        title: "提示",
        content: "是否点踩",
        success: async (modalRes) => {
          if (modalRes.confirm) {
            await this.$api.add("storeup", {
              userid: this.data.user.id,
              name: this.data.detail.shangpinmingcheng,
              picture: this.data.detail.tupian || '',
              refid: this.data.detail.id,
              tablename: "ershoushangpin",
              type: "22"
            });
            this.data.detail.crazilynum = parseInt(this.data.detail.crazilynum) + 1;
            await this.$api.update("ershoushangpin", this.data.detail);
            this.$utils.msg("点踩成功");
            this.setData({ crazilyFlag: 1 });
          }
        }
      });
    }
  },

  // 添加缺失的事件处理方法
  __l(event) {
    // 处理组件生命周期事件
    console.log('组件生命周期事件:', event);
  },

  __e(event) {
    // 处理组件自定义事件
    const { type, detail, currentTarget } = event;
    console.log('组件自定义事件:', type, detail, currentTarget);
    
    // 从 data-event-opts 中解析事件处理函数
    if (currentTarget && currentTarget.dataset && currentTarget.dataset.eventOpts) {
      const eventOpts = currentTarget.dataset.eventOpts;
      console.log('事件选项:', eventOpts);
      
      // 查找tap事件处理器
      const tapHandler = eventOpts.find(opt => opt[0] === 'tap');
      if (tapHandler && tapHandler[1] && tapHandler[1].length > 0) {
        const handlerInfo = tapHandler[1][0];
        const handlerName = handlerInfo[0];
        
        console.log('调用事件处理器:', handlerName);
        
        // 调用对应的方法
        if (this[handlerName] && typeof this[handlerName] === 'function') {
          this[handlerName](event);
          return;
        } else {
          console.warn('找不到事件处理方法:', handlerName);
        }
      }
    }
    
    // 根据事件类型进行处理
    switch (type) {
      default:
        console.log('未处理的事件类型:', type);
    }
  }
});